#define  _CRT_SECURE_NO_WARNINGS 1

#include"list.h"

void LTPrint(LTNode* phead)
{
	assert(phead);

	printf("<=>head<=>");
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

LTNode* BuyLTNode(LTDatatype x)
{
	LTNode* head = (LTNode*)malloc(sizeof(LTNode));
	if (head == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	head->next = NULL;
	head->prev = NULL;
	head->data = x;

	return head;
}

LTNode* LTInit()
{
	LTNode* phead = BuyLTNode(-1);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

//void LTDestroy(LTNode* phead)
//{
//	assert(phead);
//
//}

void LTPushBack(LTNode* phead, LTDatatype x)
{
	assert(phead);

	/*LTNode* newnode = BuyLTNode(x);
	LTNode* tail = phead->prev;
	
	tail->next = newnode;
	newnode->prev = tail;
	phead->prev = newnode;
	newnode->next = phead;*/

	LTInsert(phead, x);
}

bool LTEmpty(LTNode* phead)
{
	/*if (phead->next == NULL)
	{
		return true;
	}
	else
	{
		return false;
	}*/

	return phead == phead->next;
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;
	
	tailprev->next = phead;
	phead->prev = tailprev;
	free(tail);
	tail = NULL;
}

void LTPushFront(LTNode* phead, LTDatatype x)
{
	assert(phead);

	/*LTNode* newnode = BuyLTNode(x);

	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;*/

	LTInsert(phead->next, x);
}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next);

	LTNode* first = phead->next;

	phead->next = first->next;
	first->next->prev = phead;
	free(first);
	first = NULL;
}

void LTInsert(LTNode* pos, LTDatatype x)
{
	assert(pos);

	LTNode* newnode = BuyLTNode(x);
	
	//pos->prev   newnode   pos   
	LTNode* posprev = pos->prev;
	posprev->next = newnode;
	newnode->prev = posprev;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);

	//posprev  pos  posnext
	LTNode* posprev = pos->prev;
	LTNode* posnext = pos->next;
	posprev->next = posnext;
	posnext->prev = posprev;
	free(pos);
	pos = NULL;
}

